<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, watch, nextTick, computed } from 'vue'
import { Search, Plus, Remove } from '@element-plus/icons-vue'
import { permissionMap, getPermissionId, setUserPermissions } from '@/utils/permission.js'
import AuthButton from '@/components/AuthButton.vue'

// 设置当前用户权限（模拟超级管理员权限）
setUserPermissions([
  'user:management:add',
  'user:management:export',
  'user:management:import',
  'user:management:batchDelete',
  'user:management:search',
  'user:management:reset',
  'user:management:edit',
  'user:management:view',
  'user:management:delete',
  'permission:role:search',
  'permission:role:reset',
  'permission:role:create',
  'permission:role:edit',
  'permission:role:toggle',
  'permission:role:authorize'
])
const toggleStatus = (role) => {
  const actionText = role.status === 'normal' ? '停用' : '启用'
  ElMessageBox.confirm(`确定要${actionText}角色 "${role.name}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const index = tableData.value.findIndex((r) => r.id === role.id)
      if (index !== -1) {
        tableData.value[index].status = tableData.value[index].status === 'normal' ? 'stopped' : 'normal'
        handleSearch() // 重新应用筛选
        ElMessage({
          type: 'success',
          message: `${actionText}成功`,
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: `已取消${actionText}操作`,
      })
    })
}

// 搜索表单
const searchForm = reactive({
  roleName: '',
  status: ''
})

// 创建/修改角色
const createDialogVisible = ref(false)
const editDialogVisible = ref(false)
const createFormRef = ref(null)
const editFormRef = ref(null)
const createForm = reactive({
  name: '',
  description: ''
})
const editForm = reactive({
  id: null,
  name: '',
  description: '',
  status: ''
})

// 表单验证规则
const createFormRules = reactive({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ]
})

const editFormRules = reactive({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ]
})

// 打开创建对话框
const openCreateDialog = () => {
  // 重置表单
  createForm.name = ''
  createForm.description = ''
  createDialogVisible.value = true
}

// 确认创建
const handleCreate = () => {
  createFormRef.value.validate((valid) => {
    if (valid) {
      const newRole = {
        id: Date.now(), // 简单生成唯一ID
        name: createForm.name,
        description: createForm.description,
        status: 'stopped' // 默认状态为停用
      }
      tableData.value.push(newRole)
      handleReset() // 重置搜索并显示完整列表
      createDialogVisible.value = false
      ElMessage.success('创建成功')
    }
  })
}

// 打开修改对话框
const openEditDialog = (role) => {
  // 填充表单
  editForm.id = role.id
  editForm.name = role.name
  editForm.description = role.description
  editForm.status = role.status
  editDialogVisible.value = true
}

// 确认修改
const handleUpdate = () => {
  editFormRef.value.validate((valid) => {
    if (valid) {
      const role = tableData.value.find(r => r.id === editForm.id)
      if (role) {
        role.name = editForm.name
        role.description = editForm.description
        role.status = editForm.status
      }
      handleSearch() // 重新应用筛选
      editDialogVisible.value = false
      ElMessage.success('修改成功')
    }
  })
}

// 角色列表数据
const tableData = ref([
  { id: 1, name: '超级管理员', description: '拥有所有权限', status: 'normal' },
  { id: 2, name: '教育局', description: '负责区域内学校的心理健康工作', status: 'normal' },
  { id: 3, name: '学校', description: '负责本校学生的心理健康管理', status: 'stopped' },
  { id: 4, name: '心理老师', description: '负责具体的心理咨询和教学工作', status: 'normal' }
])

const displayTableData = ref([...tableData.value])

const statusOptions = [
  { label: '正常', value: 'normal' },
  { label: '停用', value: 'stopped' }
]

const getStatusType = (status) => (status === 'normal' ? 'success' : 'danger')
const getStatusText = (status) => (status === 'normal' ? '正常' : '停用')

// 授权对话框
const authorizeDialogVisible = ref(false)
const currentRole = ref(null)
const permissionTreeRef = ref(null)
const filterText = ref('')

// 完整的权限树数据（包含按钮级权限）
const permissionTreeData = ref([
    {
        id: 1,
        label: '用户',
        children: [
            { 
                id: 11, 
                label: '用户管理',
                children: [
                    { id: 111, label: '新增用户' },
                    { id: 112, label: '导出用户' },
                    { id: 113, label: '导入用户' },
                    { id: 114, label: '批量删除' },
                    { id: 115, label: '搜索' },
                    { id: 116, label: '重置' },
                    { id: 117, label: '编辑用户' },
                    { id: 118, label: '查看用户' },
                    { id: 119, label: '删除用户' }
                ]
            },
            { 
                id: 12, 
                label: '用户档案',
                children: [
                    { id: 121, label: '查看档案' },
                    { id: 122, label: '下载PDF报告' }
                ]
            },
            { 
                id: 13, 
                label: '组织结构',
                children: [
                    { id: 131, label: '导入组织' },
                    { id: 132, label: '保存组织' },
                    { id: 133, label: '新增下级' },
                    { id: 134, label: '编辑组织' },
                    { id: 135, label: '删除组织' }
                ]
            }
        ],
    },
    {
        id: 2,
        label: '心理测评',
        children: [
            { 
                id: 21, 
                label: '添加评测',
                children: [
                    { id: 211, label: '添加评测' },
                    { id: 212, label: '选择班级' },
                    { id: 213, label: '重置表单' },
                    { id: 214, label: '确认添加' }
                ]
            },
            { 
                id: 22, 
                label: '报告记录',
                children: [
                    { id: 221, label: '查询记录' },
                    { id: 222, label: '重置条件' },
                    { id: 223, label: '删除记录' }
                ]
            },
            { 
                id: 23, 
                label: '团测进度',
                children: [
                    { id: 231, label: '添加团测' },
                    { id: 232, label: '查询进度' },
                    { id: 233, label: '重置条件' },
                    { id: 234, label: '完成情况' },
                    { id: 235, label: '编辑团测' },
                    { id: 236, label: '删除团测' },
                    { id: 237, label: '生成二维码' },
                    { id: 238, label: '同步数据' }
                ]
            },
            { 
                id: 24, 
                label: '团体报告',
                children: [
                    { id: 241, label: '查询报告' },
                    { id: 242, label: '刷新数据' },
                    { id: 243, label: '查看团体报告' },
                    { id: 244, label: '下载PDF' }
                ]
            }
        ],
    },
    {
        id: 3,
        label: '预警干预',
        children: [
            { 
                id: 31, 
                label: '预警概览',
                children: [
                    { id: 311, label: '查看概览' }
                ]
            },
            { 
                id: 32, 
                label: '新增预警',
                children: [
                    { id: 321, label: '添加预警' },
                    { id: 322, label: '导出记录' },
                    { id: 323, label: '查询预警' },
                    { id: 324, label: '重置条件' }
                ]
            },
            { 
                id: 33, 
                label: '预警名单',
                children: [
                    { id: 331, label: '查看名单' }
                ]
            },
            { 
                id: 34, 
                label: '预警评估',
                children: [
                    { id: 341, label: '添加评估' },
                    { id: 342, label: '查询评估' },
                    { id: 343, label: '重置条件' },
                    { id: 344, label: '导入评估' },
                    { id: 345, label: '下载模板' },
                    { id: 346, label: '保存评估' },
                    { id: 347, label: '编辑评估' },
                    { id: 348, label: '删除评估' }
                ]
            },
            { 
                id: 35, 
                label: '预警干预',
                children: [
                    { id: 351, label: '添加干预' },
                    { id: 352, label: '查询干预' },
                    { id: 353, label: '重置条件' },
                    { id: 354, label: '上传文件' },
                    { id: 355, label: '下载模板' },
                    { id: 356, label: '创建干预' },
                    { id: 357, label: '重置表单' }
                ]
            },
            { 
                id: 36, 
                label: '预警设置',
                children: [
                    { id: 361, label: '刷新设置' },
                    { id: 362, label: '添加设置' },
                    { id: 363, label: '保存设置' },
                    { id: 364, label: '编辑设置' },
                    { id: 365, label: '删除设置' }
                ]
            }
        ],
    },
    {
        id: 4,
        label: '咨询预约',
        children: [
            { 
                id: 41, 
                label: '咨询师',
                children: [
                    { id: 411, label: '添加咨询师' },
                    { id: 412, label: '查询咨询师' },
                    { id: 413, label: '重置条件' },
                    { id: 414, label: '编辑咨询师' },
                    { id: 415, label: '删除咨询师' }
                ]
            },
            { 
                id: 42, 
                label: '预约记录',
                children: [
                    { id: 421, label: '添加预约' },
                    { id: 422, label: '查询预约' },
                    { id: 423, label: '重置条件' },
                    { id: 424, label: '确认预约' },
                    { id: 425, label: '取消预约' },
                    { id: 426, label: '选择用户' },
                    { id: 427, label: '保存预约' }
                ]
            },
            { 
                id: 43, 
                label: '咨询记录',
                children: [
                    { id: 431, label: '添加记录' },
                    { id: 432, label: '查询记录' },
                    { id: 433, label: '重置条件' },
                    { id: 434, label: '编辑记录' },
                    { id: 435, label: '删除记录' },
                    { id: 436, label: '保存记录' }
                ]
            }
        ],
    },
    {
        id: 5,
        label: '心理课程',
        children: [
            { 
                id: 51, 
                label: '课程列表',
                children: [
                    { id: 511, label: '进入课程' },
                    { id: 512, label: '返回列表' }
                ]
            }
        ],
    },
    {
        id: 6,
        label: '个人中心',
        children: [
            { 
                id: 61, 
                label: '个人中心',
                children: [
                    { id: 611, label: '编辑信息' },
                    { id: 612, label: '修改密码' },
                    { id: 613, label: '保存信息' },
                    { id: 614, label: '确认修改密码' }
                ]
            },
            { 
                id: 62, 
                label: '权限',
                children: [
                    { id: 621, label: '角色管理' },
                    { id: 622, label: '授权管理' }
                ]
            }
        ],
    }
])

// 模拟每个角色已有的权限（包含按钮级权限）
const rolePermissions = reactive({
  1: [1, 11, 111, 112, 113, 114, 115, 116, 117, 118, 119, 12, 121, 122, 13, 131, 132, 133, 134, 135, 2, 21, 211, 212, 213, 214, 22, 221, 222, 223, 23, 231, 232, 233, 234, 235, 236, 237, 238, 24, 241, 242, 243, 244, 3, 31, 311, 32, 321, 322, 323, 324, 33, 331, 34, 341, 342, 343, 344, 345, 346, 347, 348, 35, 351, 352, 353, 354, 355, 356, 357, 36, 361, 362, 363, 364, 365, 4, 41, 411, 412, 413, 414, 415, 42, 421, 422, 423, 424, 425, 426, 427, 43, 431, 432, 433, 434, 435, 436, 5, 51, 511, 512, 6, 61, 611, 612, 613, 614, 62, 621, 622], // 超级管理员
  2: [1, 11, 111, 112, 113, 114, 115, 116, 117, 118, 119, 12, 121, 122, 13, 131, 132, 133, 134, 135, 2, 21, 211, 212, 213, 214, 22, 221, 222, 223, 23, 231, 232, 233, 234, 235, 236, 237, 238, 24, 241, 242, 243, 244, 3, 31, 311, 32, 321, 322, 323, 324, 33, 331, 34, 341, 342, 343, 344, 345, 346, 347, 348, 35, 351, 352, 353, 354, 355, 356, 357, 36, 361, 362, 363, 364, 365], // 教育局
  3: [1, 11, 111, 112, 115, 116, 117, 118, 12, 121, 122, 2, 21, 211, 212, 213, 214, 22, 221, 222, 223, 6, 61, 611, 612, 613, 614], // 学校
  4: [2, 21, 211, 212, 213, 214, 22, 221, 222, 223, 23, 231, 232, 233, 234, 235, 236, 237, 238, 24, 241, 242, 243, 244, 4, 41, 411, 412, 413, 414, 415, 42, 421, 422, 423, 424, 425, 426, 427, 43, 431, 432, 433, 434, 435, 436, 6, 61, 611, 612, 613, 614], // 心理老师
})

// 监听筛选文本变化
watch(filterText, (val) => {
  permissionTreeRef.value.filter(val)
})

// 树节点筛选方法
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.includes(value)
}

// 打开授权对话框
const openAuthorizeDialog = (role) => {
  currentRole.value = role
  authorizeDialogVisible.value = true
  // 使用 nextTick 确保 DOM 更新完毕
  nextTick(() => {
    permissionTreeRef.value.setCheckedKeys(rolePermissions[role.id] || [], false)
  })
}

// 确认授权
const handleAuthorize = () => {
  const checkedKeys = permissionTreeRef.value.getCheckedKeys()
  const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
  rolePermissions[currentRole.value.id] = [...checkedKeys, ...halfCheckedKeys]
  authorizeDialogVisible.value = false
  ElMessage.success('授权成功')
}

// 搜索
const handleSearch = () => {
  displayTableData.value = tableData.value.filter(item => {
    const nameMatch = searchForm.roleName ? item.name.toLowerCase().includes(searchForm.roleName.toLowerCase()) : true;
    const statusMatch = searchForm.status ? item.status === searchForm.status : true;
    return nameMatch && statusMatch;
  });
}

// 重置
const handleReset = () => {
  searchForm.roleName = ''
  searchForm.status = ''
  displayTableData.value = [...tableData.value]
}
</script>

<template>
  <div class="permission-management">
    <!-- 搜索和操作区域 -->
    <div class="toolbar">
      <el-form :model="searchForm" inline>
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" style="width: 240px;"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 240px;">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <AuthButton type="primary" permission="permission:role:search" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </AuthButton>
          <AuthButton @click="handleReset" permission="permission:role:reset">
            <el-icon><Remove /></el-icon> 重置
          </AuthButton>
        </el-form-item>
      </el-form>
      <AuthButton type="success" permission="permission:role:create" @click="openCreateDialog">
        <el-icon><Plus /></el-icon> 创建角色
      </AuthButton>
    </div>

    <!-- 角色列表 -->
    <div class="table-container">
      <el-table :data="displayTableData" style="width: 100%" border>
        <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
        <el-table-column prop="name" label="名称" align="center"></el-table-column>
        <el-table-column prop="description" label="描述" min-width="200"></el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" align="center">
          <template #default="{ row }">
          <AuthButton size="small" type="primary" @click="openEditDialog(row)" permission="permission:role:edit">修改</AuthButton>
          <AuthButton size="small" :type="row.status === 'normal' ? 'danger' : 'success'" @click="toggleStatus(row)" permission="permission:role:toggle">
            {{ row.status === 'normal' ? '停用' : '启用' }}
          </AuthButton>
          <AuthButton size="small" type="warning" @click="openAuthorizeDialog(row)" permission="permission:role:authorize">授权</AuthButton>
        </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 授权对话框 -->
    <el-dialog
      v-model="authorizeDialogVisible"
      :title="'为角色 ' + (currentRole ? currentRole.name : '') + ' 授权'"
      width="600px"
    >
      <el-input v-model="filterText" placeholder="输入关键字进行过滤" style="margin-bottom: 15px;"></el-input>
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTreeData"
        :props="{ children: 'children', label: 'label' }"
        show-checkbox
        node-key="id"
        :filter-node-method="filterNode"
        default-expand-all
      ></el-tree>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="authorizeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAuthorize">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 创建角色对话框 -->
    <el-dialog v-model="createDialogVisible" title="创建角色" width="500px">
      <el-form :model="createForm" label-width="80px" ref="createFormRef" :rules="createFormRules">
        <el-form-item label="名称" prop="name" required>
          <el-input v-model="createForm.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="createForm.description" type="textarea" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCreate">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog v-model="editDialogVisible" title="修改角色" width="500px">
      <el-form :model="editForm" label-width="80px" ref="editFormRef" :rules="editFormRules">
        <el-form-item label="名称" prop="name" required>
          <el-input v-model="editForm.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editForm.description" type="textarea" placeholder="请输入角色描述"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="正常" value="normal"></el-option>
            <el-option label="停用" value="stopped"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdate">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.permission-management {
  padding: 20px;
  background-color: #fff;
  min-height: 100%;
}
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}
.table-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
}
.el-icon {
  margin-right: 4px;
}
</style>
